package com.xhj.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xhj.entity.Order;
import com.xhj.service.OrderService;
import com.xhj.util.JwtUtil;
import com.xhj.util.ResultEntity;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;


/**
 * 订单(TOrder)表控制层
 *
 * @author makejava
 * @since 2021-03-11 11:34:16
 */
@CrossOrigin
@RestController
@RequestMapping("/order/")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @RequestMapping("createOrder/{courseId}")
    public ResultEntity saveOrder(@PathVariable String courseId, HttpServletRequest request){
        String memberId = JwtUtil.getMemberIdByJwtToken(request);
        if (StringUtils.isEmpty(memberId)) return ResultEntity.failedWithMessage("请重新登录！").setCode(28004);
        String orderId = orderService.saveOrder(courseId,memberId);
        return ResultEntity.successWithData().data("orderId",orderId);
    }

    @RequestMapping("info/{orderNo}")
    public ResultEntity getInfoById(@PathVariable String orderNo){
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no",orderNo);
        Order order = orderService.getOne(queryWrapper);
        return ResultEntity.successWithData().data("order",order);
    }

    @ApiOperation(value = "根据客户Id和课程id查询该客户是否购买了该课程")
    @RequestMapping("isBuyCourse/{memberId}/{courseId}")
    public boolean isBuyCourse(@PathVariable("memberId") String memberId,
                               @PathVariable("courseId") String courseId){
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("member_id",memberId).eq("course_id",courseId).eq("status", 1);
        int count = orderService.count(queryWrapper);
        // count 为1 则说明已购买
        return count == 1;
    }
}